#!/usr/bin/env bash
# vim:noexpandtab:ts=2:sw=2:

set -e
set -o pipefail

main() {
	local target="${1}"
	shift
	local go_bootstrap_version="${1}"
	shift

	sanity_checks "$@"

	echo "---> using bootstrap version ${go_bootstrap_version}"
	eval "$(./gimme "${go_bootstrap_version}")"

	"_test_${target}" "$@"
}

die() {
	printf >&2 '***> %s\n' "$*"
	exit 1
}

can_resolve_version() {
	local GIMME_TYPE='binary'
	export GIMME_TYPE
	local want="${1}"
	local verbose="${2:-false}"
	local ev r
	ev=0
	r="$(./gimme --resolve "${want}" 2>/dev/null)" || ev=$?
	if ! [[ -n "${r}" ]]; then
		die "no output resolving input version '${want}'"
	fi
	case $ev in
	0) true ;;
	2) die "failed to resolve version '${want}'" ;;
	*) die "unexpected error resolving version '${want}'" ;;
	esac
	if $verbose; then
		printf '%s\n' "${r}"
	fi
}

sanity_checks() {
	echo "---> doing sanity checks that all known versions resolve"
	local v got
	for v in ${RUNTESTS_EXTRA_RESOLVE:-}; do
		can_resolve_version "$v"
	done
	for v in "$@" 1; do
		case "${v}" in
		master) continue ;;
		go*) v="${v#go}" ;;
		esac
		[[ $v == 1 ]] || can_resolve_version "${v}"
		if [[ "${v}" =~ ^[0-9.]+$ ]]; then
			got="$(can_resolve_version "${v}.x" true)"
			[[ "$got" =~ ^[0-9.]+$ ]] || die "resolved '${v}.x' to non-stable '${got}'"
		fi
	done
}

_test_native() {
	for v in "${@}"; do
		echo "---> eval \$(./gimme ${v})"
		(
			eval "$(./gimme "${v}")"
			[[ "$(go env GOOS)" == "$(go env GOHOSTOS)" && "$(go env GOARCH)" == "$(go env GOHOSTARCH)" ]] || exit 1
		) || exit 1
	done
}

_test_arm() {
	for v in "${@}"; do
		echo "---> eval \$(GIMME_OS=linux GIMME_ARCH=arm ./gimme ${v})"
		(
			eval "$(GIMME_OS=linux GIMME_ARCH=arm ./gimme "${v}")"
			[[ "$(go env GOOS)" == 'linux' && "$(go env GOARCH)" == 'arm' ]] || exit 1
		) || exit 1
	done
}

_test_arm64() {
	for v in "${@}"; do
		if [[ "$(echo "${v}" | tr -d '[:alpha:]' | tr -d '.' | cut -b1-2)" -lt 15 && "${v}" != "tip" && "${v}" != "master" ]]; then
			echo "---> skipping ${v} because it probably won't work o_o"
			continue
		fi
		if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then cgo=1; else cgo=0; fi
		echo "---> eval \$(GIMME_OS=linux GIMME_ARCH=arm64 GIMME_CGO_ENABLED=$cgo ./gimme $v)"
		(
			eval "$(GIMME_OS=linux GIMME_ARCH=arm64 GIMME_CGO_ENABLED=$cgo ./gimme "${v}")"
			[[ "$(go env GOOS)" == 'linux' && "$(go env GOARCH)" == 'arm64' ]] || exit 1
		) || exit 1
	done
}

main "$@"
